﻿namespace dPet.Application.Services.Implementation
{
	using AutoMapper;
	using dPet.Application.DataObjects;
	using dPet.Domain.Models;
	using dPet.Domain.Repositories;
	using dPet.Domain.Specifications;
	using dPet.Infrastructure.Logging;
	using Hangerd;
	using Hangerd.Repository;

	public class TemplateService : ServiceBase, ITemplateService
	{
		#region Repository

		private readonly IHospitalRepository _hospitalRepository;
		private readonly IBillTemplateRepository _billTemplateRepository;

		#endregion

		#region Services

		#endregion

		#region Constructors

		public TemplateService(
			IRepositoryContext unitOfWork,
			IHospitalRepository hospitalRepository,
			IBillTemplateRepository billTemplateRepository)
			: base(unitOfWork)
		{
			_hospitalRepository = hospitalRepository;
			_billTemplateRepository = billTemplateRepository;
		}

		#endregion

		#region Sale Bill Template

		public MessagedResult<bool> SaveBillTemplate(string hospitalId, BillTemplateDto templateDto, IOperator @operator)
		{
			return TryLoggedOperate(@operator, "配置管理", "更新票据模板配置", (ref BillTemplate template) =>
			{
				var hospital = _hospitalRepository.Get(hospitalId, false);

				if (hospital == null)
				{
					throw new HangerdException("医院信息不存在");
				}

				var spec = BillTemplateSpecifications.HospitalIdEquals(hospitalId);

				template = _billTemplateRepository.Get(spec, true) ?? new BillTemplate(hospital);

				template.BillTitle = templateDto.BillTitle;
				template.ShowAddress = templateDto.ShowAddress;
				template.Address = templateDto.Address;
				template.ShowPhoneNumber = templateDto.ShowPhoneNumber;
				template.PhoneNumber = templateDto.PhoneNumber;
				template.ShowFaxNumber = templateDto.ShowFaxNumber;
				template.FaxNumber = templateDto.FaxNumber;
				template.FootText = templateDto.FootText;

				if (template.IsTransient())
				{
					_billTemplateRepository.Add(template, true);
				}
				else
				{
					_billTemplateRepository.Update(template, true);
				}

				UnitOfWork.Commit();

				return true;
			});
		}

		public BillTemplateDto GetBillTemplate(string hospitalId)
		{
			var spec = BillTemplateSpecifications.HospitalIdEquals(hospitalId);
			var template = _billTemplateRepository.Get(spec, false);

			return Mapper.Map<BillTemplate, BillTemplateDto>(template);
		}

		#endregion
	}
}
